package com.kuang.pool.utils;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * Created by 郭浩 on 2020/9/23 14:29
 */
public class MyDataSource implements DataSource {
    private static LinkedList<Connection> pool = new LinkedList<>();

    private static Integer initCount = 0;
    //池子一开始就要先创建好，所以需要放在静态代码块里面
    static{
        //将配置文件读成流到类加载器中
        InputStream resourceAsStream = MyconnectionPool.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();

        try {
            properties.load(resourceAsStream);
            //得到相应的值
            String driverClassName = properties.getProperty("driverClassName");
            String url = properties.getProperty("url");
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String initialConnectionCount = properties.getProperty("initialConnectionCount");
            initCount = Integer.parseInt(initialConnectionCount);
            //反射加载静态代码，创建一个Drivermanger
            Class.forName(driverClassName);
            //根据initcount的数量初始化连接池的数量
            for (Integer i = 0; i < initCount; i++) {
                Connection connection = DriverManager.getConnection(url, user, password);
                pool.add(connection);
            }

        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
    @Override
    public Connection getConnection() throws SQLException {
        if(pool.size() >= 0.3 * initCount ){
            return pool.removeLast();
        }
        DynamicExpand();
        return pool.getLast();
    }

    private void DynamicExpand() {

    }
    public void returnConnection(Connection connection){
        pool.add(connection);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
